<?php


/**请求示例
写   http://域名/dx.class.php?path=路径&key=key值&value=写入的value值&type=write
读   http://域名/dx.class.php?path=路径&key=key值&value=无数据时的默认值&type=read
**/


$path=$_REQUEST["path"];
$key=$_REQUEST["key"];
$value=$_REQUEST["value"];
$type=$_REQUEST["type"];

if ($type=="read")
{
    $Q=new dx($path);
    echo $Q->get($key,$value);
}

if ($type=="write")
{
   $Q=new dx($path);
   $Q->xx($key,$value);
}


/****/

/*
  写入
  $Q=new dx("测试/群号.txt");
  $Q->xx("QQ","1");  //返回boolean类型
*/

/*
  读取
  $Q=new dx("测试/群号.txt");
   echo $Q->get("QQ","默认值");
*/



class dx {

      public $path;
      
    public function __construct($path) {
        $this->path=$path;
    }
    
    public function get ($key,$default)
    {
       if(!$this->Has())
       {
          return false;
       }
       $T=$this->read($this->path);
       $T=json_decode($T,true);
       if (is_array($T))
       {
          $T=$T[$key];
       }else{
          $T=$default;
       }
       return $T;
    }
    
    public function xx ($key,$value)
    {
       if(!$this->Has())
       {
          return false;
       }
       $T=$this->read($this->path);
       $T=json_decode($T,true);
       if (is_array($T))
       {
          $T[$key]=$value;
          $T=json_encode($T,JSON_UNESCAPED_UNICODE);
          file_put_contents($this->path,$T);
       }else{
          $G=array();
          $G[$key]=$value;
          $G=json_encode($G,JSON_UNESCAPED_UNICODE);
          $this->write($this->path,$G);
       }
       return true;
    }
    
   
   public function read($file) {
    $myfile = fopen($file, "r") or die("文件不存在？");
     $text=fread($myfile,filesize($file)+1);
      fclose($myfile);
        return $text;
        }

    
    public function Has(){
        if (!file_exists($this->path))
        {
           if(!mkdir($this->path, 0777,true)){
                return false;
           }else{
              $this->deldir($this->path);
              $this->write($this->path,"");
           }
        }
        return true;
    }
    
    public function write($file,$n){
     $myfile = fopen($file, "w") or die("无法打开文件");
      fwrite($myfile,$n);
       fclose($myfile);
}
    
    
    
    public function deldir($dir) {

  //先删除目录下的文件：

  $dh=opendir($dir);
  while ($file=readdir($dh)) {
    if($file!="." && $file!="..") {
      $fullpath=$dir."/".$file;
      if(!is_dir($fullpath)) {
          unlink($fullpath);
      } else {
          deldir($fullpath);
      }
    }
  }
  closedir($dh);
  //删除当前文件夹：
  if(rmdir($dir)) {
    return true;
  } else {
    return false;
  }
}


}


?>